import { io } from 'socket.io-client';
import { store } from './store';
import { mockChatMessages } from './mockData';

// Socket.io connection - change URL to match your backend
const SOCKET_URL = 'http://localhost:8080';

// Flag to use mock socket (set to false when backend is ready)
const USE_MOCK_SOCKET = true;

let socket;
let mockSocket = null;

// Create a mock socket for development without backend
function createMockSocket() {
  if (mockSocket) return mockSocket;
  
  // List of simulated online users
  const onlineUsers = [
    { id: 2, username: 'user2', position: { x: 10, y: 1, z: 10 } },
    { id: 3, username: 'user3', position: { x: -15, y: 1, z: 5 } }
  ];
  
  // Initial chat messages
  store.chatMessages = [...mockChatMessages];
  
  // Setup mock socket events
  mockSocket = {
    connected: true,
    
    // Mock emit event
    emit: (event, data) => {
      console.log('Mock socket emitting:', event, data);
      
      // Handle different events
      switch (event) {
        case 'updatePosition':
          // Update user position and notify others after delay
          setTimeout(() => {
            // Simulate random movement of other users
            onlineUsers.forEach(user => {
              user.position.x += (Math.random() - 0.5) * 2;
              user.position.z += (Math.random() - 0.5) * 2;
              
              // Emit movement event
              if (mockSocket.onUserMoved) {
                mockSocket.onUserMoved(user);
              }
            });
          }, 2000);
          break;
          
        case 'sendMessage':
          // Add message to store after short delay
          setTimeout(() => {
            store.addChatMessage(data);
            
            // Simulate dealer response after delay
            if (data.dealerId) {
              setTimeout(() => {
                const dealerResponse = {
                  senderId: 1000 + data.dealerId, // Create dealer ID
                  senderName: data.dealerId === 1 ? 'Premium Auto Group' : 'City Motors',
                  message: getRandomDealerResponse(),
                  dealerId: data.dealerId,
                  timestamp: new Date().toISOString()
                };
                
                store.addChatMessage(dealerResponse);
                
                if (mockSocket.onNewMessage) {
                  mockSocket.onNewMessage(dealerResponse);
                }
              }, 1500);
            }
          }, 300);
          break;
      }
    },
    
    // Mock disconnect
    disconnect: () => {
      console.log('Mock socket disconnected');
      mockSocket.connected = false;
    },
    
    // Event callbacks
    onUserConnected: null,
    onUserDisconnected: null,
    onUserMoved: null,
    onNewMessage: null,
    
    // Mock on event
    on: (event, callback) => {
      console.log('Mock socket registering event:', event);
      
      // Store callback for each event type
      switch (event) {
        case 'userConnected':
          mockSocket.onUserConnected = callback;
          // Trigger initial users list
          setTimeout(() => {
            callback([...onlineUsers, { 
              id: store.user.id, 
              username: store.user.username,
              position: store.position
            }]);
          }, 500);
          break;
          
        case 'userDisconnected':
          mockSocket.onUserDisconnected = callback;
          break;
          
        case 'userMoved':
          mockSocket.onUserMoved = callback;
          break;
          
        case 'newMessage':
          mockSocket.onNewMessage = callback;
          break;
      }
    }
  };
  
  return mockSocket;
}

// Helper function to get random dealer responses
function getRandomDealerResponse() {
  const responses = [
    "Thanks for your message! How can I help you today?",
    "That sounds great! Is there anything specific you'd like to know about the car?",
    "I'm available to schedule a test drive. Would tomorrow work for you?",
    "This model has been very popular. Would you like me to reserve it for you?",
    "We also have similar models in different colors if you'd prefer.",
    "Our financing team can help with payment options. Would you like details?",
    "The car comes with a comprehensive 3-year warranty."
  ];
  
  return responses[Math.floor(Math.random() * responses.length)];
}

export default {
  // Initialize socket connection
  connect(userId, username) {
    if (USE_MOCK_SOCKET) {
      socket = createMockSocket();
    } else {
      socket = io(SOCKET_URL, {
        auth: {
          userId,
          username
        }
      });
    }
    
    this.setupListeners();
    return socket;
  },
  
  // Disconnect socket
  disconnect() {
    if (socket) {
      socket.disconnect();
    }
  },
  
  // Set up event listeners
  setupListeners() {
    // User connected event
    socket.on('userConnected', (users) => {
      store.updateConnectedUsers(users);
      console.log('Connected users updated:', users);
      
      // Add avatars for other users
      users.forEach(user => {
        if (user.id !== store.user.id) {
          if (window.cityScene) {
            window.cityScene.addAvatar(user);
          }
        }
      });
    });
    
    // User disconnected event
    socket.on('userDisconnected', (users) => {
      store.updateConnectedUsers(users);
      console.log('User disconnected, remaining users:', users);
    });
    
    // User moved event
    socket.on('userMoved', (userData) => {
      // Update other user's position in the store
      const userIndex = store.connectedUsers.findIndex(user => user.id === userData.id);
      if (userIndex !== -1) {
        store.connectedUsers[userIndex].position = userData.position;
      }
      
      // Update avatar in 3D scene
      if (window.cityScene) {
        window.cityScene.addAvatar(userData);
      }
    });
    
    // New chat message event
    socket.on('newMessage', (message) => {
      store.addChatMessage(message);
    });
  },
  
  // Send position update to server
  sendPosition(x, y, z) {
    if (socket && socket.connected) {
      socket.emit('updatePosition', { 
        userId: store.user.id,
        id: store.user.id,
        username: store.user.username,
        position: { x, y, z } 
      });
      store.updatePosition(x, y, z);
    }
  },
  
  // Send chat message
  sendChatMessage(message, dealerId = null) {
    if (socket && socket.connected) {
      socket.emit('sendMessage', {
        senderId: store.user.id,
        senderName: store.user.username,
        message,
        dealerId,
        timestamp: new Date().toISOString()
      });
    }
  }
}; 